package com.xiaoke.api.controller;

import com.xiaoke.api.service.AddressService;
import com.xiaoke.entity.Address;
import com.xiaoke.entity.User;
import com.xiaoke.shiro.SecurityService;
import com.xiaoke.util.common.AjaxMsg;
import com.xiaoke.util.common.ValidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/address")
public class AddressController {
    @Autowired
    private AddressService addressService;
    @Autowired
    private SecurityService securityService;

    @PostMapping("/delete")
    public AjaxMsg delete(String id){
        addressService.delete(id);
        return new AjaxMsg();
    }

    @PostMapping("/save")
    public AjaxMsg saveOrUpdate(Address address){
        User user = securityService.getCurrentUser();
        address.setUserId(user.getId());
        if(ValidUtil.isEmpty(address.getId())||"0".equals(address.getId())){
            addressService.insert(address);
        }else {
            addressService.update(address);
        }
        return new AjaxMsg();
    }

    @GetMapping("/detail")
    public AjaxMsg detail(String id){
        return new AjaxMsg(addressService.findById(id));
    }

    @GetMapping("/list")
    public AjaxMsg list(){
        User user = securityService.getCurrentUser();
        return new AjaxMsg(addressService.findByUser(user.getId()));
    }
}

